package net.dreamlu.controller.api;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import net.dreamlu.api.oauth.OauthOsc;
import net.dreamlu.api.util.TokenUtil;
import net.dreamlu.common.WebUtils;
import net.dreamlu.common.ext.base.BaseController;
import net.dreamlu.model.User;
import net.dreamlu.model.WbLogin;
import net.dreamlu.common.utils.EmailUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.Locale;
import java.util.Map;

/**
 * 开源中国api登录
 * @author L.cm
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @date Jun 24, 2013 9:58:25 PM
 */
public class OscLoginController extends BaseController {
    private static final String SESSION_STATE = "_SESSION_STATE_OSC_";

    public void index() {
        logger.error("进入osc authorize api...");
        try {
            String state = TokenUtil.randomState();
            setSessionAttr(SESSION_STATE, state);
            redirect(OauthOsc.me().getAuthorizeUrl(state));
        } catch (Exception e) {
            logger.error(e.getMessage());
            redirect("/");
        }
    }

    /**
     * osc回调
     * @Title: callback
     * @return void    返回类型
     * 返回json:<url>http://www.oschina.net/openapi/docs/openapi_user</url>
     */
    public void callback() {
        logger.error("进入osc callback...");
        String code = getPara("code");
        String state = getPara("state");
        String session_state = getSessionAttr(SESSION_STATE);
        // 取消了授权
        if (StrKit.isBlank(state) || StrKit.isBlank(session_state) || !state.equals(session_state) || StrKit.isBlank(code)) {
            redirect("/admin");
            return;
        }
        removeSessionAttr(SESSION_STATE);
        try{
            OauthOsc osc = OauthOsc.me();
            // 使用code换取accessToken
            String accessToken = osc.getTokenByCode(getPara("code"));
            // 获取用户信息
            Map<String, Object> userInfo = osc.getUserInfo(accessToken);
            logger.error(null != userInfo ? userInfo.toString() : "userInfo is null...");
            String type = "osc";
            // {id=813039, email=596392912@qq.com, location=北京 海淀, name=孤独的3, gender=male, avatar=http://static.oschina.net/uploads/user/406/813039_50.jpg?t=1348824049000, url=http://my.oschina.net/qq596392912}
            String openid = String.valueOf(userInfo.get("id")); // osc id
            String nickname = userInfo.get("name").toString();  // osc name
            String photoUrl = userInfo.get("avatar").toString();// osc 头像
            String email = userInfo.get("email").toString();    // osc email
            String url = userInfo.get("url").toString();        // osc 博客url
            //===========================================
            // 发送动弹，DreamLu博客使用 osc api登录成功...
            osc.tweetPub(accessToken, "@" + nickname + " \t使用osc api成功登录[DreamLu博客](http://www.dreamlu.net/)");
            //===========================================
            // 第三方登录实体，后面部分没怎么改
            WbLogin login = WbLogin.dao.findByOpenID(openid, type);
            logger.error("login1:\t" + login);
            if(null == login) {
                login = new WbLogin();
                login.setOpenId(openid);
                login.setType(type);
                login.setHeadPhoto(photoUrl);
                login.setCreatetime(new Date());
                login.setStatus(WbLogin.STATUS_N);
                login.setNickname(nickname);
                login.save();
            }
            logger.error("login2:\t" + login);
            // 是否邮件校验通过
            int status = login.getStatus();
            if (null != login.getId() && WbLogin.STATUS_N == status) {
                if (null == login.getUserId()) {
                    setAttr("nouser", true);
                }
                // 跳转到绑定页
                setAttr("id", login.getId());
                setAttr("type", type);
                setAttr("nickname", nickname);
                setAttr("photourl", photoUrl);
                setAttr("email", email);
                setAttr("blogurl", url);
                render("binding.jsp");
                return;
            }
            if (WbLogin.STATUS_Y == status) {
                User user = User.dao.findById(login.getUserId());
                WebUtils.loginUser(this, user, false);
            }
        }catch(Exception e){
            logger.error(e.getMessage());
        }
        redirect("/admin");
    }

    /**
     * 开源中国git钩子，用于项目自动发布
     */
    public void hook() {
        logger.info("init git hook...");
        String password = getPara("password", "");
        String gitPwd   = PropKit.get("git.pwd");
        if (password.equals(gitPwd)) {
            final String shPath = PropKit.get("sh.build");
            final String shMail = PropKit.get("sh.mail");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 得先发邮件，要不然tomcat都关闭了
                        EmailUtils.sendMail(EmailUtils.MailData.New()
                                .to(shMail)
                                .subject("git hook build OK!")
                                .content(DateFormatUtils.format(new Date(), "yyyy年MM月dd日 HH时mm分ss秒", Locale.CHINA) + " jnode 自动编译重启中...")
                        );
                        Runtime.getRuntime().exec(shPath);
                    } catch (Exception e) {
                        logger.error("build.sh IO error...");
                    }
                }
            }).start();
        }
        renderNull();
        return;
    }
}
